package com.tj.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.tj.common.Result;
import com.tj.dto.UserDTO;
import com.tj.pojo.User;
import com.tj.service.UserService;
import com.tj.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping
    private Result<String> login(@RequestBody Map<String,String> m, HttpSession httpSession, HttpServletRequest httpServletRequest) {
        //1.获取账号和密码
        String username = m.get("username");
        String password = m.get("password");


        //2.获取数据库是对应账号
        User user = userService.getUser(username);

        //3.判断是否为空,如果空返回结果
        if(user==null)
            return Result.error("账号不存在");

        //4.判断密码是否正确
        if(!password.equals(user.getPassword()))
            return  Result.error("密码错误");

        //5.将User转化为UserDTO
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String,Object> userMap=BeanUtil.beanToMap(userDTO,new HashMap<>(), CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));

        //6.使用JWT生成登录令牌token
        String token = JwtUtil.getJWT(userMap,1000*60*60L);

        //7.返回携带token的结果
        return Result.success(token);
    }
}
